package com.avic.rong.course.activity.otherActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.course.bean.PeiXunDownBean;
import com.avic.rong.course.showapi.PeiXunDownFileApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PeiXunDownDataActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.down1)
    TextView down1;
    @BindView(R.id.down2)
    TextView down2;
    @BindView(R.id.down3)
    TextView down3;
    @BindView(R.id.down4)
    TextView down4;
    @BindView(R.id.down5)
    TextView down5;
    @BindView(R.id.down6)
    TextView down6;
    @BindView(R.id.down7)
    TextView down7;
    @BindView(R.id.xg_ll_kj)
    LinearLayout xgLlKj;
    @BindView(R.id.xg_ll_kj1)
    LinearLayout xgLlKj1;
    @BindView(R.id.xg_ll_kj2)
    LinearLayout xgLlKj2;
    @BindView(R.id.xg_ll_sp)
    LinearLayout xgLlSp;
    @BindView(R.id.xg_ll_sp1)
    LinearLayout xgLlSp1;
    @BindView(R.id.xg_ll_sp2)
    LinearLayout xgLlSp2;
    @BindView(R.id.xg_ll_yp)
    LinearLayout xgLlYp;
    @BindView(R.id.xg_ll_yp1)
    LinearLayout xgLlYp1;
    @BindView(R.id.xg_ll_yp2)
    LinearLayout xgLlYp2;
    @BindView(R.id.xg_ll_yp3)
    LinearLayout xgLlYp3;
    @BindView(R.id.xt_ll_yp)
    LinearLayout xtLlYp;
    @BindView(R.id.xite_text1)
    TextView xiteText1;
    @BindView(R.id.xt_ll_sp1)
    LinearLayout xtLlSp1;
    @BindView(R.id.xite_text2)
    TextView xiteText2;
    @BindView(R.id.xt_ll_sp2)
    LinearLayout xtLlSp2;
    private List<PeiXunDownBean.SPListBean> spList = new ArrayList<>();
    private List<PeiXunDownBean.SPListBean> ypList = new ArrayList<>();
    private List<PeiXunDownBean.SPListBean> kjList = new ArrayList<>();
    private List<PeiXunDownBean.SPListBean> xtList = new ArrayList<>();
    private String fileServer = "http://video.rongrong.huazhi365.com/uploadFile/onlinestudy";
    private static String filePath = "/shidoe";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(context, "下载完成！\n文件存储路径:" + filePath, Toast.LENGTH_SHORT).show();
                Log.e("cjx", "path:" + filePath);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pei_xun_down_data);
        ButterKnife.bind(this);
        ivRight.setImageResource(R.mipmap.slh);
        tvTitle.setText("相关资料");

        //设备API大于6.0时，主动申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 0);

            }
        }

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopup(PeiXunDownDataActivity.this, llRoot);
            }
        });
        String courseId = getIntent().getStringExtra(PeiXunClassMuLuActivity.COURSESID);
        initDownData(courseId);
        initListener();
    }

    private void initListener() {

    }

    private void initDownData(String courseId) {
        if (!SharedPreferencesUtil.isLogin()) {
            PeiXunDownFileApi classMuLuApi = new PeiXunDownFileApi(this, simpleOnNextListener, courseId, "");
            classMuLuApi.setCache(false);
            HttpManager.getInstance().doHttpDeal(classMuLuApi);
        } else {
            PeiXunDownFileApi classMuLuApi = new PeiXunDownFileApi(this, simpleOnNextListener, courseId, SharedPreferencesUtil.getLoginToken());
            Log.e("cjx", "login_token" + SharedPreferencesUtil.getLoginToken());
            classMuLuApi.setCache(false);
            HttpManager.getInstance().doHttpDeal(classMuLuApi);
        }

    }


    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(PeiXunDownDataActivity.this, subjects.getMsg());
                Log.e("cjx", subjects.getMsg());
                return;
            }
            PeiXunDownBean bean = (PeiXunDownBean) subjects.getResult();
            if (bean.getSPList().size() == 0) {
                xgLlSp.setVisibility(View.GONE);
                xgLlSp1.setVisibility(View.GONE);
                xgLlSp2.setVisibility(View.GONE);
            } else {
                xgLlSp.setVisibility(View.VISIBLE);
                spList.addAll(bean.getSPList());
                try {
                    if (spList.size() == 1) {
                        xgLlSp1.setVisibility(View.VISIBLE);
                        xgLlSp2.setVisibility(View.GONE);
                        down3.setText(spList.get(0).getName());
                    } else if (spList.size() == 2) {
                        xgLlSp1.setVisibility(View.VISIBLE);
                        xgLlSp2.setVisibility(View.VISIBLE);
                        down3.setText(spList.get(0).getName());
                        down4.setText(spList.get(1).getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bean.getYPList().size() == 0) {
                xgLlYp.setVisibility(View.GONE);
                xgLlYp1.setVisibility(View.GONE);
                xgLlYp2.setVisibility(View.GONE);
                xgLlYp3.setVisibility(View.GONE);
            } else {
                xgLlYp.setVisibility(View.VISIBLE);
                ypList.addAll(bean.getYPList());
                try {
                    if (ypList.size() == 1) {
                        xgLlYp1.setVisibility(View.VISIBLE);
                        xgLlYp2.setVisibility(View.GONE);
                        xgLlYp3.setVisibility(View.GONE);
                        down5.setText(ypList.get(0).getName());
                    } else if (ypList.size() == 2) {
                        xgLlYp1.setVisibility(View.VISIBLE);
                        xgLlYp2.setVisibility(View.VISIBLE);
                        xgLlYp3.setVisibility(View.GONE);
                        down5.setText(ypList.get(0).getName());
                        down6.setText(ypList.get(1).getName());
                    } else if (ypList.size() == 3) {
                        xgLlYp1.setVisibility(View.VISIBLE);
                        xgLlYp2.setVisibility(View.VISIBLE);
                        xgLlYp3.setVisibility(View.VISIBLE);
                        down5.setText(ypList.get(0).getName());
                        down6.setText(ypList.get(1).getName());
                        down7.setText(ypList.get(2).getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bean.getKJList().size() == 0) {
                xgLlKj.setVisibility(View.GONE);
                xgLlKj1.setVisibility(View.GONE);
                xgLlKj2.setVisibility(View.GONE);
            } else {
                xgLlKj.setVisibility(View.VISIBLE);
                kjList.addAll(bean.getKJList());
                try {
                    if (kjList.size() == 1) {
                        xgLlKj1.setVisibility(View.VISIBLE);
                        xgLlKj2.setVisibility(View.GONE);
                        down1.setText(kjList.get(0).getName());
                    } else if (kjList.size() == 2) {
                        xgLlKj1.setVisibility(View.VISIBLE);
                        xgLlKj2.setVisibility(View.VISIBLE);
                        down1.setText(kjList.get(0).getName());
                        down2.setText(kjList.get(1).getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bean.getXTList().size() == 0) {
                xtLlYp.setVisibility(View.GONE);
                xtLlSp1.setVisibility(View.GONE);
                xtLlSp2.setVisibility(View.GONE);
            } else {
                xtLlYp.setVisibility(View.VISIBLE);
                xtList.addAll(bean.getXTList());
                try {
                    if (xtList.size() == 1) {
                        xiteText1.setVisibility(View.VISIBLE);
                        xiteText2.setVisibility(View.GONE);
                        xiteText1.setText(xtList.get(0).getName());
                    } else if (xtList.size() == 2) {
                        xiteText1.setVisibility(View.VISIBLE);
                        xiteText2.setVisibility(View.VISIBLE);
                        xiteText1.setText(xtList.get(0).getName());
                        xiteText2.setText(xtList.get(1).getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            down1.setOnClickListener(PeiXunDownDataActivity.this);
            down2.setOnClickListener(PeiXunDownDataActivity.this);
            down3.setOnClickListener(PeiXunDownDataActivity.this);
            down4.setOnClickListener(PeiXunDownDataActivity.this);
            down5.setOnClickListener(PeiXunDownDataActivity.this);
            down6.setOnClickListener(PeiXunDownDataActivity.this);
            down7.setOnClickListener(PeiXunDownDataActivity.this);
            xiteText1.setOnClickListener(PeiXunDownDataActivity.this);
            xiteText2.setOnClickListener(PeiXunDownDataActivity.this);
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "培训课时目录列表数据：" + e.getMessage());
        }
    };

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void addListener() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.down1:
                if (kjList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应课件", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(kjList.get(0).getName());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(kjList.get(0).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    }else {
                        downLoad(fileServer + kjList.get(0).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down2:
                if (kjList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应课件", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(kjList.get(1).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(kjList.get(1).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    }else {
                        downLoad(fileServer + kjList.get(1).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down3:
                if (spList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应视频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(spList.get(0).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(spList.get(0).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    } else {
                        downLoad(fileServer + spList.get(0).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down4:
                if (spList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应视频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(spList.get(1).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(spList.get(1).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    } else {
                        downLoad(fileServer + spList.get(1).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down5:
                if (ypList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应音频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(ypList.get(0).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }  else if (TextUtils.isEmpty(ypList.get(0).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    }else {
                        downLoad(fileServer + ypList.get(0).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down6:
                if (ypList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应音频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(ypList.get(1).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }  else if (TextUtils.isEmpty(ypList.get(1).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    }else {
                        downLoad(fileServer + ypList.get(1).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.down7:
                if (ypList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应音频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(ypList.get(2).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(ypList.get(2).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    } else {
                        downLoad(fileServer + ypList.get(2).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.xite_text1:
                if (xtList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应音频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(xtList.get(0).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(xtList.get(0).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    }  else {
                        downLoad(fileServer + xtList.get(0).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
            case R.id.xite_text2:
                if (xtList.size() == 0) {
                    Toast.makeText(context, "您还未购买相应音频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    String fileName = getFileName(xtList.get(1).getFilePath());
                    if (StringUtil.isEmpty(fileName)) {
                        Toast.makeText(context, "未购买该培训", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(xtList.get(1).getFilePath())){
                        ToastTools.showPublicToast("您还没有权限，请购买权限");
                    } else {
                        downLoad(fileServer + xtList.get(1).getFilePath(), fileName, PeiXunDownDataActivity.this, handler);
                    }
                }
                break;
        }
    }

    public static void downLoad(final String path, final String FileName, Context context, Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {
                            FileUtils fileUtils = new FileUtils();
                            fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));//指定文件保存路径，代码看下一步
                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                            }
                            handler.sendEmptyMessage(1);
                            Log.e("cjx", "下载完成");
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static class FileUtils {
        String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";
        public FileUtils() {
            File file = new File(path);
            /**
             *如果文件夹不存在就创建
             */
            if (!file.exists()) {
                file.mkdirs();
            }
        }

        /**
         * 创建一个文件
         *
         * @param FileName 文件名
         * @return
         */
        public File createFile(String FileName) {
            filePath = path + "/"+FileName;
            return new File(path, FileName);
        }
    }

    public String getFileName(String name) {
        if (StringUtil.isEmpty(name)) {
            return "";
        } else {
            int i = name.lastIndexOf("/");
            return name.substring(i + 1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
